package stucts.form;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

public class Structs_xml {
	Structs_xml(){
		
	}
	
	@SuppressWarnings("unchecked")
	public static Map<String,Xmlbean> stucs_xml(String realpath) throws JDOMException, IOException{
		SAXBuilder saxbuilder = new SAXBuilder();
		Document document = saxbuilder.build(new File(realpath));
		Element root = document.getRootElement();
		
		Map<String,Xmlbean> xmap =new HashMap<String, Xmlbean>();
		
		Element actionMapping = root.getChild("action-mapping");
		List<Element> mappings = actionMapping.getChildren();
		for (Element m : mappings) {
			Xmlbean xmlBean = new Xmlbean();
			String name =  m.getAttributeValue("name");
			xmlBean.setBeanName(name);
			Element actionForm = root.getChild("formbeans");
			List<Element> elements = actionForm.getChildren();
			for (Element e : elements) {
				String actionFormName =  e.getAttributeValue("name");
				
				if(actionFormName.equals(name)){
					xmlBean.setFormClass(e.getAttributeValue("class"));
					break;
				}
			}
			
			String cla = m.getAttributeValue("class");
			xmlBean.setActionClass(cla);
			String path = m.getAttributeValue("path");
			xmlBean.setPath(path);
			List<Element> fs = m.getChildren();
			Map<String ,String> forMap = new HashMap<String, String>();
			for (Element f : fs) {
				String fname= f.getAttributeValue("name");
				String fvalue = f.getAttributeValue("value");
				forMap.put(fname, fvalue);
			}
			xmlBean.setForwardMap(forMap);
			System.out.println(path);
			System.out.println(xmlBean);
			xmap.put(path, xmlBean);
		}
		return xmap;
	}
	
	
//	public static void main(String[] args) {
//		try {
//			Map<String,Xmlbean> xx = new HashMap<String, Xmlbean>();
//			xx = stucs_xml();
//			Set<String> set = xx.keySet();
//			
//			for (Iterator<String> iterator = set.iterator(); iterator.hasNext();) {
//				String keyPath =  iterator.next();
//				System.out.println(keyPath);
//				System.out.println(xx.get(keyPath));
//			}
//			Collection ss =  xx.values();
//			for (Iterator iterator = ss.iterator(); iterator.hasNext();) {
//				Object object = (Object) iterator.next();
//				System.out.println(object);
//			}
//			
//		} catch ( Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} 
//	}
//	
	
}
